package com.zbcz.crm.adapter

import android.R
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.Spinner
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.RecyclerView
import com.zbcz.crm.CrmApplication
import com.zbcz.crm.CustomerAddActivity.Companion.CUSTOMER_ADDRESS
import com.zbcz.crm.CustomerAddActivity.Companion.CUSTOMER_INDUSTRY
import com.zbcz.crm.CustomerAddActivity.Companion.CUSTOMER_LEVEL
import com.zbcz.crm.CustomerAddActivity.Companion.CUSTOMER_MOBILE
import com.zbcz.crm.CustomerAddActivity.Companion.CUSTOMER_NAME
import com.zbcz.crm.CustomerAddActivity.Companion.CUSTOMER_PHONE
import com.zbcz.crm.CustomerAddActivity.Companion.CUSTOMER_SOURCE
import com.zbcz.crm.CustomerAddActivity.Companion.CUSTOMER_WEBSITE
import com.zbcz.crm.CustomerAddActivity.Companion.DEAL_STATUS
import com.zbcz.crm.CustomerAddActivity.Companion.REMARKS
import com.zbcz.crm.VisitorAddActivity
import com.zbcz.crm.bean.CommonListBean
import com.zbcz.crm.bean.CommonSpinnerBean
import com.zbcz.crm.bean.Customer
import com.zbcz.crm.databinding.ItemCommonListBinding
import com.zbcz.crm.sp.SharedPreferencesManager
import com.zbcz.crm.util.ToastUtils
import com.zbcz.crm.util.UPLOAD_FORMAT_WHOLE
import com.zbcz.crm.util.getCurrentDateFormatted

class CommonListAdapter(private val dataList: List<CommonListBean>) :
    RecyclerView.Adapter<CommonListAdapter.ViewHolder>() {

    companion object {
        private val industries = arrayOf(
            CommonSpinnerBean("请选择", ""),
            CommonSpinnerBean("IT", "0"),
            CommonSpinnerBean("金融业", "1"),
            CommonSpinnerBean("房地产", "2"),
            CommonSpinnerBean("商业服务", "3"),
            CommonSpinnerBean("运输/物流", "4"),
            CommonSpinnerBean("生产", "5"),
            CommonSpinnerBean("政府", "6"),
            CommonSpinnerBean("文化传媒", "7")
        )

        private val customerSources = arrayOf(
            CommonSpinnerBean("请选择", ""),
            CommonSpinnerBean("促销", "0"),
            CommonSpinnerBean("搜索引擎", "1"),
            CommonSpinnerBean("广告", "2"),
            CommonSpinnerBean("转介绍", "3"),
            CommonSpinnerBean("线上注册", "4"),
            CommonSpinnerBean("线上询价", "5"),
            CommonSpinnerBean("预约上门", "6"),
            CommonSpinnerBean("陌拜", "7"),
            CommonSpinnerBean("电话咨询", "8"),
            CommonSpinnerBean("邮件咨询", "9")
        )

        private val dealStatus = arrayOf(
            CommonSpinnerBean("请选择", ""),
            CommonSpinnerBean("已成交", "0"),
            CommonSpinnerBean("未成交", "1")
        )

        private val customerLevels = arrayOf(
            CommonSpinnerBean("请选择", ""),
            CommonSpinnerBean("A（重点客户）", "0"),
            CommonSpinnerBean("B（普通客户）", "1"),
            CommonSpinnerBean("C（非优先客户）", "2")
        )


        fun getSpinnerArray(type: Int): Array<CommonSpinnerBean>? {
            return when (type) {
                CUSTOMER_INDUSTRY -> industries
                DEAL_STATUS -> dealStatus
                CUSTOMER_LEVEL -> customerLevels
                CUSTOMER_SOURCE -> customerSources
                else -> null
            }
        }

        const val TAG = "CommonListAdapter"


    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = ItemCommonListBinding.inflate(inflater, parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = dataList[position]
        holder.bind(item)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    fun getItem(position: Int): CommonListBean {
        return dataList[position]
    }

    inner class ViewHolder(private val binding: ItemCommonListBinding) :
        RecyclerView.ViewHolder(binding.root) {

        init {
            binding.edContent.addTextChangedListener {
                getItem(adapterPosition).value = it.toString()
            }

            binding.spSelect.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?, view: View, position: Int, id: Long
                ) {
                    // 获取选中的选项
                    val selectedOption = binding.spSelect.selectedItem as? CommonSpinnerBean
                    Log.i(VisitorAddActivity.TAG, "selected$selectedOption")
                    getItem(adapterPosition).value = selectedOption?.value.toString()
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                    // 当没有选项被选中时的处理逻辑
                }
            }
        }

        fun bind(item: CommonListBean) {
            binding.apply {
                // 设置标题
                tvTitle.text = item.title
                edContent.hint = item.hintText
                if (adapterPosition == dataList.size - 1) {
                    ivDivider.visibility = View.GONE
                } else {
                    ivDivider.visibility = View.VISIBLE
                }
            }
            if (item.type == CUSTOMER_SOURCE || item.type == CUSTOMER_INDUSTRY || item.type == CUSTOMER_LEVEL || item.type == DEAL_STATUS) {
                binding.rightArrow.visibility = View.VISIBLE
                binding.edContent.isEnabled = false
                binding.edContent.visibility = View.GONE
                binding.spSelect.visibility = View.VISIBLE
                getSpinnerArray(item.type)?.let {
                    initSpinner(
                        binding.root.context, binding.spSelect, it, adapterPosition
                    )
                }
                //binding.spSelect.selectedItem
            } else {
                binding.rightArrow.visibility = View.GONE
                binding.edContent.visibility = View.VISIBLE
                binding.edContent.isEnabled = true
                binding.spSelect.visibility = View.GONE
                binding.edContent.setText(item.value.toString())
            }

            if (item.type == REMARKS) {
                binding.redStar.visibility = View.GONE
            }

        }

        // 方法用于获取当前项目的值
        fun getCurrentValue(): String {
            return if (binding.edContent.visibility == View.VISIBLE && binding.edContent.isEnabled) {
                binding.edContent.text.toString()
            } else {
                val selectedOption = binding.spSelect.selectedItem as? CommonSpinnerBean
                selectedOption?.value.toString() ?: ""
            }
        }
    }

    fun getAllEditTextValues(): List<CommonListBean> {
        val values = mutableListOf<CommonListBean>()
        for (i in 0 until itemCount) {
            values.add(getItem(i))
        }
        return values
    }

    fun createCustomRequest(): Customer? {
        val request = Customer()

        for (data in dataList) {
            val value = data.value.toString()
            when (data.type) {
                CUSTOMER_ADDRESS -> {
                    if (!isValidAddress(value)) {
                        ToastUtils.show("地址格式不正确")
                        return null
                    }
                    request.customerDetailedAddress = value
                }

                CUSTOMER_INDUSTRY -> {
                    if (value.isEmpty()) {
                        ToastUtils.show("请选择客户行业")
                        return null
                    }
                    request.customerIndustry = value
                }

                CUSTOMER_LEVEL -> {
                    if (value.isEmpty()) {
                        ToastUtils.show("请选择客户级别")
                        return null
                    }
                    request.customerLevel = value
                }

                CUSTOMER_NAME -> {
                    if (value.isEmpty()) {
                        ToastUtils.show("请输入客户名称")
                        return null
                    }
                    request.customerName = value
                }

                CUSTOMER_PHONE -> {
                    request.customerPhoneNumber = value
                }

                CUSTOMER_MOBILE -> {
                    if (!isValidMobile(value)) {
                        ToastUtils.show("手机号格式不正确")
                        return null
                    }
                    request.customerPhone = value
                }

                CUSTOMER_SOURCE -> {
                    if (value.isEmpty()) {
                        ToastUtils.show("请选择客户来源")
                        return null
                    }
                    request.customerSource = value
                }

                CUSTOMER_WEBSITE -> {
                    if (value.isEmpty()) {
                        ToastUtils.show("请输入客户网址")
                        return null
                    }
                    request.customerWebsite = value
                }

                DEAL_STATUS -> {
                    if (value.isEmpty()) {
                        ToastUtils.show("请选择成交状态")
                        return null
                    }
                    request.dealStatus = value
                }

                REMARKS -> {
                    request.notes = value
                }
            }
        }

        // 将其他设置放在最后
        request.apply {
            createBy =
                SharedPreferencesManager.getUserInfo(CrmApplication.mApplication)?.createBy.toString()
            createTime =
                SharedPreferencesManager.getUserInfo(CrmApplication.mApplication)?.createTime.toString()
            id = ""
            sysOrgCode = ""
            updateBy =
                SharedPreferencesManager.getUserInfo(CrmApplication.mApplication)?.username.toString()
            updateTime = getCurrentDateFormatted(UPLOAD_FORMAT_WHOLE).toString()
        }

        Log.i(TAG, request.toString())

        return request
    }


    private fun isValidMobile(mobile: String?): Boolean {
        // 简单的手机号验证，可以根据实际情况进行修改
        val regex = Regex("^1[0-9]{10}\$")
        return !mobile.isNullOrEmpty() && regex.matches(mobile)
    }

    private fun isValidPhoneNumber(phoneNumber: String?): Boolean {
        // 简单的固定电话号码验证，可以根据实际情况进行修改
        val regex = Regex("\"^1[3-9]\\\\d{9}\$\".toRegex()")
        return !phoneNumber.isNullOrEmpty() && regex.matches(phoneNumber)
    }

    private fun isValidAddress(address: String?): Boolean {
        // 简单的地址格式验证，可以根据实际情况进行修改
        return !address.isNullOrEmpty() && address.length <= 100
    }


    private fun initSpinner(
        context: Context, spinner: Spinner, options: Array<CommonSpinnerBean>, position: Int
    ) {
        // 创建适配器
        val adapter = CustomSpinnerAdapter(context, options)
        adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item)
        // 设置适配器
        spinner.adapter = adapter

//        // 设置选项选中监听器
//        // 设置选项选中监听器
//        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
//            override fun onItemSelected(
//                parent: AdapterView<*>?,
//                view: View,
//                position: Int,
//                id: Long
//            ) {
//                // 获取选中的选项
//                val selectedOption = options[position]
//                Log.i(VisitorAddActivity.TAG, "selected$selectedOption")
//
//                // 处理选项选中后的逻辑，这里简单地显示一个Toast
//                //Toast.makeText(this@VisitorAddActivity, "你选择了：$selectedOption", Toast.LENGTH_SHORT).show()
//            }
//
//            override fun onNothingSelected(parent: AdapterView<*>?) {
//                // 当没有选项被选中时的处理逻辑
//            }
//        }
    }
}
